import React,{ useState ,useReducer} from 'react'
import './App.css'
import Header from './component/Header'
import Home from './component/Home'
import Login from './component/Login'
import './App.css'

// 用户的登录状态需要共享.可以跨层级调用
// 想让子组件拿到数据，那就在父组件让context暴露出去
export const AuthContext = React.createContext();

const initialState = { //初始状态
    isAuthenticated:false,
    user:null,
    token:null
}

const reducer = (state,action)=>{
    switch(action.type){
      case 'LOGIN':
        return{
          ...state,
          isAuthenticated:action.payload.isAuthenticated,
          user:action.payload.user
        }
      case 'LOGOUT':
        return{
          ...state,
          isAuthenticated:false,
          user:null,
          token:null
        }
      default:
        return state
    }
}

function App() {
 
  // 数据的共享在这里处理。state就是Reducer的状态树。跨层级跨组件，实现状态共享并数据响应
const [state,dispatch] = useReducer(reducer,initialState)
// console.log(state,'-----------');

  return (
   
    <AuthContext.Provider value={{
      state,
      dispatch
    }}> 
      <Header />
      <div className="App">
        {/* 是否登录，已经登录进入home页面，没有进入login页面 */}
        {!state.isAuthenticated?<Login /> : <Home />} 
      </div>
    </AuthContext.Provider>
  )
}

export default App
